# coding: utf-8

import os

import config
import jsonp as jsonHandler

from initialize import logger


class FileHandler(object):
    def __init__(self):
        self.result_file = config.RESULT_FILE
        self.queried_file = config.QUERIED_FILE
        self.querying_file = config.QUERYING_FILE
        self.user_data_file = config.USER_DATA_FILE
        self.queried_list = []

    def __write(self, file, content):
        self.__write_file(file, 'a+', content)

    def __write_file(self, file, model, content):
        with open(file, model) as f:
            f.write(content)

    def __read(self, file):
        all_list = []
        if not os.path.exists(file):
            return all_list
        with open(file, 'r') as f:
            for line in f:
                line = line.replace(os.linesep, '')
                if line:
                    all_list.append(line)
        return all_list

    def read_querying(self, file=None):
        if file is None:
            file = self.querying_file
        querys = []
        query_string_list = self.__read(file)
        for query_string in query_string_list:
            query_array = query_string.split('|')
            querys.append((query_array[0], query_array[1]))
        return querys

    def read_queried(self):
        if self.queried_list:
            return self.queried_list
        query_string_list = self.__read(self.queried_file)
        for query_string in query_string_list:
            query_array = query_string.split('|')
            policy_no = query_array[0]
            status = int(query_array[1]) == 1
            self.queried_list.append((policy_no, status))
        return self.queried_list

    def get_queried(self, policy_no):
        querys = self.read_queried()
        if querys:
            querys = [t for t in querys if t[0] == policy_no]
        return querys and querys[0] or None

    def check_queried(self, policy_no):
        if not policy_no:
            logger.info('policy no [{0}] is null, skip current query!'.format(policy_no))
            return False
        query_tuple = self.get_queried(policy_no)
        if query_tuple is not None:
            if query_tuple[1]:
                logger.info('policy no [{0}] already queried, skip current query!'.format(policy_no))
            else:
                logger.info('policy no [{0}] not found info, skip current query!'.format(policy_no))
            logger.info()
            return False
        return True

    def exists_queried(self, policy_no):
        return self.get_queried(policy_no) is not None

    def write_queried(self, policy_no, status):
        self.__write(self.queried_file, '{0}|{1}{2}'.format(policy_no, status, os.linesep))
        self.queried_list.append((policy_no, int(status) == 1))

    def write_result(self, policy_info):
        insurances = []
        for insurance_type in policy_info.insurance_type_list:
            insurances.append({
                u'保障项目': insurance_type.guarantee_project,
                u'保额': insurance_type.sum_insured,
                u'标准保费': insurance_type.annual_premium,
                u'费率浮动系数': insurance_type.rate_floating_coefficient,
                u'实缴保费': insurance_type.payment_premium,
                u'费率浮动事由': insurance_type.rate_floating_cause
            })
        policy_info_dict = {
            u'投保人姓名': policy_info.policy_holder_name,
            u'险种名称': policy_info.policy_name,
            u'保单号': policy_info.policy_no,
            u'保险期间': policy_info.policy_date_time,
            u'保险责任开始时间': policy_info.policy_begin_date_time,
            u'保单状态': policy_info.policy_status,
            u'被保险人姓名': policy_info.policy_the_name,
            u'被保险人证件号码': policy_info.policy_the_no,
            u'车牌号': policy_info.license_plate_no,
            u'车架号': policy_info.frame_number,
            u'发动机号': policy_info.engine_number,
            u'核定载客数量': policy_info.nuclear_load_number,
            u'核定载重质量': policy_info.nuclear_load_weight,
            u'车辆类型': policy_info.vehicle_type,
            u'车辆使用性质': policy_info.vehicle_usage,
            u'商品险种信息': insurances,
            u'应缴保费': policy_info.pay_premium,
            u'已缴保费': policy_info.paid_premium,
            u'缴费方式': policy_info.pay_method,
            u'缴费日期': policy_info.pay_date,
            u'欠缴保费': policy_info.unpaid_premium,
            u'渠道类型': policy_info.channel_type,
            u'代理机构/人名称': policy_info.agency_name,
            u'机构代码/职业资格证书代码': policy_info.agency_code,
            u'支付方式': policy_info.payment_method,
            u'支付对象': policy_info.payment_object
        }
        policy_no = policy_info_dict[u'保单号']
        self.write_queried(policy_no, 1)
        string = '{0}--------------{0}'.format(os.linesep)
        for (key, value) in policy_info_dict.items():
            if isinstance(value, list):
                string += u'{0}:{1}'.format(key, os.linesep)
                for dic in value:
                    string += '\t--------------{0}'.format(os.linesep)
                    for (_key, _value) in dic.items():
                        string += u'\t{0}:{1}{2}'.format(_key, str(_value).replace(os.linesep, ''), os.linesep)
            else:
                string += u'{0}:{1}{2}'.format(key, value, os.linesep)
        # current_directory = os.path.join(RESULT_DIRECTORY, TIMESTAMP)
        # if not os.path.exists(current_directory):
        #     os.makedirs(current_directory)
        # self.result_file = os.path.join(current_directory, '{0}.txt'.format(policy_no))
        self.__write(self.result_file, string + os.linesep)

    def write_result_json(self, policy_info):
        policy_no = policy_info['policy_no']
        self.write_queried(policy_no, 1)
        self.__write(self.result_file, u'{0}{1}'.format(jsonHandler.to_json(policy_info).decode('unicode_escape'), os.linesep))

    def write_user_data(self, data):
        string = jsonHandler.to_json(data)
        self.__write(self.user_data_file, string)
